package com.lpc.databindingtest2;

import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * 功能:
 * <p>
 * 描述:
 * <p>
 * Created by lipc0113 on 2018/7/26.
 */
public class MyRecyclerViewAdapter<T> extends RecyclerView.Adapter {

    private final Activity activity;
    private final List<T> list;
    private final int layoutId;
    private final int redid;
    private final LayoutInflater inflater;

    public MyRecyclerViewAdapter(Activity activity, List<T> list, int layoutId, int redid) {

        this.activity = activity;
        this.inflater = LayoutInflater.from(activity);
        this.list = list;
        this.layoutId = layoutId;
        this.redid = redid;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        ViewDataBinding dataBinding = DataBindingUtil.inflate(inflater, layoutId, viewGroup, false);

        return new MyHolder(dataBinding.getRoot(), dataBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

        if(viewHolder instanceof MyHolder){

            MyHolder holder = (MyHolder)viewHolder;
            holder.getDataBinding().setVariable(redid, list.get(i));
            holder.getDataBinding().executePendingBindings();
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public static class MyHolder extends RecyclerView.ViewHolder {

        private final ViewDataBinding dataBinding;

        public MyHolder(@NonNull View itemView, ViewDataBinding dataBinding) {
            super(itemView);
            this.dataBinding = dataBinding;
        }

        public ViewDataBinding getDataBinding() {
            return dataBinding;
        }
    }
}
